package net.blogways.ordermgr.mail.service;

import com.asiainfo.bpc.exception.BusiException;
import com.asiainfo.bpc.utils.ToolFactory;
import net.blogways.ordermgr.mail.entity.Mail;
import net.blogways.ordermgr.mail.factory.TemplateFactory;
import net.blogways.ordermgr.mail.util.MailUtils;
import net.blogways.ordermgr.mail.util.MapUtils;
import net.blogways.ordermgr.util.RescodeConstants;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class MailService{

  private final Logger logger = LoggerFactory.getLogger(MailService.class);

  private Mail mail;

  private static final Pattern PATTERN
          = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");

  public void sendMail(Map message) throws Exception {
    logger.debug("message" + message);
    String body = null;
    mail = (Mail) ToolFactory.getInstance().getContext().getBean("mail");
    List mailList = (List) message.get("mailList");
    logger.debug("Send Mail List---------" + mailList);
    for (int i = 0; i < mailList.size(); i++) {
      try {
        Map<String, Object> mailMap = (Map<String, Object>) mailList.get(i);
        String templateName = MapUtils.getStringValue(mailMap, "templateName");
        Map<String, Object> mailInfo = (Map<String, Object>) mailMap.get("mailInfo");
        String emailAddress = MapUtils.getStringValue(mailMap, "mailAddress");
        String copySomeone = MapUtils.getStringValue(mailMap, "copySomeone");
        Matcher matcher = PATTERN.matcher(emailAddress);
        String subject = MapUtils.getStringValue(mailMap, "title");
        Map<String, Object> attach = (Map<String, Object>) mailMap.get("attachInfo");
        if (attach != null && attach.size() != 0) {
          String attachPath = MapUtils.getStringValue(attach, "attachPath");
          EmailAttachment attachment = new EmailAttachment();
          attachment.setPath(attachPath);
          attachment.setDisposition(EmailAttachment.ATTACHMENT);
          attachment.setDescription(MapUtils.getStringValue(attach, "description"));
          attachment.setName(MapUtils.getStringValue(attach, "attachment_name"));
          mail.setAttachment(attachment);
        }
        body = TemplateFactory.printContextToTemplate(mailInfo, templateName);
        mail.setReceiver(emailAddress);
        mail.setSubject(subject);
        mail.setCopySomeone(copySomeone);
        mail.setMessage(body);
        if (!matcher.matches()) {
          logger.error("Email Address Error");
          throw new BusiException(RescodeConstants.PARAMES_EXECPTION, "邮件地址有误!");
        }
        MailUtils.sendMail(mail);
      } catch (EmailException e) {
        e.printStackTrace();
        throw new BusiException(RescodeConstants.EMAIL_EXECPTION, e.getMessage());
      }
    }

  }

  public Mail getMail() {
    return mail;
  }

  public void setMail(Mail mail) {
    this.mail = mail;
  }


}
